import { _decorator, AudioSource, Component, Label, Node, tween, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Utils')
export class Utils extends Component {
    @property({type: Node})
    flashBoardNode: Node = null!

    audioSource: AudioSource = new AudioSource()

    start() {
        this.initComponents()
    }

    /** 
     * @zh
     * 初始化组件。
    */
    initComponents() {
        this.audioSource = this.node.getComponent(AudioSource)
    }

    /** 
     * @zh
     * 让某个Label组件显示特定文本，可以显示打字机效果以及调整打字速度，开发者也可以设置回调函数。
    */
    showText(labelComp: Label, text: string, callback:Function=null, isTyping: boolean=true, typingInterval:number=0.1) {
        if (!isTyping) {
            labelComp.string = text
            if (callback) {
                callback()
            }
            return
        }

        // 打字机效果
        let scheduleCount = 0
        let typingText = ()=>{
            if (scheduleCount < text.length) {
                labelComp.string += text[scheduleCount]
                scheduleCount++
            }
            else {
                this.audioSource.stop()
                this.unschedule(typingText)
                if (callback) {
                    callback()
                }
            }
        }

        // 开始调度前要先取消上一次的调度并清空文本。
        this.unschedule(typingText)
        labelComp.string = ''

        // 开始新的调度。
        this.audioSource.play()
        this.schedule(typingText, typingInterval)
    }

    /** 
     * @zh
     * 显示flash消息。
    */
    showFlashMessage(msg: string, time: number=1) {
        this.flashBoardNode.active = true
        this.flashBoardNode.setSiblingIndex(10000)
        this.flashBoardNode.children[0].getComponent(Label).string = msg

        this.flashBoardNode.setScale(1, 0, 1)
        tween(this.flashBoardNode).to(0.05, {'scale': new Vec3(1, 1, 0)}).start()

        this.unschedule(this.hideFlashBoard)

        // 如果time是-1，则一直显示flash消息s
        if (time != -1) {
            this.scheduleOnce(this.hideFlashBoard, time)
        }
    }

    /** 
     * @zh
     * 隐藏flash板，用于计时器。
    */
    hideFlashBoard() {
        tween(this.flashBoardNode).to(0.08, {'scale': new Vec3(1, 0, 0)})
                                  .call(()=>{this.flashBoardNode.active = false})
                                  .start()
    }
}


